
package com.keycloak.admin.services;


import com.keycloak.admin.client.KeycloakAdminClient;
import com.keycloak.admin.map.ClientMap;
import com.keycloak.admin.model.params.*;
import com.keycloak.admin.model.params.vo.UserRepresentationNew;
import com.keycloak.admin.utils.KeycloakClientManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class PassengerInfoService {

    private static Logger logger = LogManager.getLogger(PassengerInfoService.class);

    @Autowired
    UserInfo userInfo;

    @Resource
    ClientMap clientMap;


    public ReturnParams openIdLogin(PhoneParams request,String clientId){

        try {

            String cell = request.getPhone();
            //根据openId去查询keycloak用户是否存在
            KeycloakAdminClient client = null;
            if (KeycloakClientManager.getClientMap(clientId) != null) {
                client = KeycloakClientManager.getClientMap(clientId);
            } else {
                client = userInfo.getMasterToken(clientId, clientMap.getClientSecret(clientId));
                KeycloakClientManager.setClientMap(clientId, client);
            }

            List<UserRepresentationNew> users = userInfo.searchUsers(cell, client);
            String loginPassword = "";
            if (users != null && users.size() > 0) {
                //去登陆获取accessToken
                Map<String, Object> attributes = users.get(0).getAttributes();
                loginPassword = attributes.get("default_password").toString().replace("[", "").replace("]", "");

            }
            //去登陆获取用户accessToken
            CreateUserPasswordParams createUserPassword = new CreateUserPasswordParams();
            createUserPassword.setCell(cell);
            createUserPassword.setPassword(loginPassword);
            ReturnParams returnParams = userInfo.userLogin(createUserPassword, clientId);
            if (returnParams.getCode() != 0) {
                return new ReturnParams(1, returnParams.getData().toString(), null);
            }

            return new ReturnParams(0, "success", returnParams.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ReturnParams(1, "error", null);

    }





}

